# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  
  before_filter :account_required

  # render new.rhtml
  def new
    redirect_back_or_default(root_path(:subdomain => current_user.company.subdomain)) if logged_in?
  end

  def create
    self.current_user = (current_subdomain.nil?) ? User.authenticate(params[:email], params[:password]) : 
                                                   User.authenticate(params[:email], params[:password], current_subdomain)
      if logged_in?
        if params[:remember_me] == "1"
          current_user.remember_me unless current_user.remember_token?
          cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
        end
        redirect_to user_path(current_user, :subdomain => current_user.company.subdomain)
       else
          flash[:error] = "Virhe kirjautumisessa. Tarkista käyttäjänimi ja salasana."
          redirect_to login_path
     end
  end

  def destroy
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default('/')
  end
end
